package com.qf.cx.simplenms.core.spi.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.qf.cx.simplenms.core.spi.Updater;
import com.qf.cx.simplenms.persist.entity.SubscriberEntity;
import com.qf.cx.simplenms.persist.entity.TopicEntity;
import com.qf.cx.simplenms.persist.service.api.SubscriberService;
import com.qf.cx.simplenms.subscriber.api.SubscriberManager;
import com.qf.cx.simplenms.subscriber.model.SubscriberModel;
import com.qf.cx.simplenms.topic.api.Topic;
import com.qf.cx.simplenms.topic.api.TopicManager;

public class SubscriberUpdater implements Updater {
	@Autowired
	private SubscriberService subscriberService;

	@Autowired
	private SubscriberManager subscriberManager;

	@Autowired
	private TopicManager topicManager;

	@Override
	public void update() {
		List<SubscriberEntity> subscribers = subscriberService.getSubscribers();
		List<SubscriberModel> list = new ArrayList<>();
		for (SubscriberEntity each : subscribers) {
			SubscriberModel subscriberModel = new SubscriberModel();
			subscriberModel.setId(each.getId());
			subscriberModel.setUrl(each.getUrl());

			List<TopicEntity> topicEntities = each.getTopicEntities();
			Set<Topic> topics = new HashSet<>();
			for (TopicEntity topicEntity : topicEntities) {
				Topic topic = topicManager.getTopic(topicEntity.getName());
				if (topic != null) {
					topics.add(topic);
				}
			}
			subscriberModel.addTopics(topics);
			list.add(subscriberModel);
		}
		subscriberManager.updateCache(list);
	}

}
